package datalayer.taglayer.TAGDAOLayer;

import java.io.File;
import java.io.IOException;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;

import Model.Album;
import Model.Nummer;
import datalayer.interfaces.IDAONummer;

public class TagDAONummer implements IDAONummer {
	
	private static TagDAONummer instance;
	
	public static TagDAONummer getInstance() {
		if (instance == null) {
			instance = new TagDAONummer();
		}
		return instance;
	}
	
	@Override
	public void LoadNummer(Nummer n) {
		String locatie = n.getLocatie();
		locatie = locatie.replace("file:///", "");
		
			
		File sourcefile = new File(locatie);
		try {
			AudioFile f = AudioFileIO.read(sourcefile);
			Tag tag = f.getTag();
			
			if (tag.getFirst(FieldKey.TITLE) == "") {
				tag.setField(FieldKey.TITLE, "unknown title");
				f.commit();
				AudioFileIO.write(f);
			}
			if (tag.getFirst(FieldKey.ARTIST)== "") {
				tag.setField(FieldKey.ARTIST, "unknown artist");
				f.commit();
				AudioFileIO.write(f);
			}
			if (tag.getFirst(FieldKey.ALBUM)== "") {
				tag.setField(FieldKey.ALBUM, "unknown album");
				f.commit();
				AudioFileIO.write(f);
			}
			
			
			n.setNaam(tag.getFirst(FieldKey.TITLE));
			n.setJaar(tag.getFirst(FieldKey.YEAR));
			n.setArtiest(tag.getFirst(FieldKey.ARTIST));
			n.setAlbum(tag.getFirst(FieldKey.ALBUM));
			n.setGenre(tag.getFirst(FieldKey.GENRE));
			n.setBitrate(f.getAudioHeader().getBitRateAsNumber());
			n.setTijdsduur(f.getAudioHeader().getTrackLength());
			
//			String rating = (tag.getFirst(FieldKey.RATING));
//			
//			if (rating == "1") {
//				n.setRating(1);
//			}
//			if (rating == "64") {
//				n.setRating(2);
//			}
//			if (rating == "128") {
//				n.setRating(3);
//			}
//			if (rating == "196") {
//				n.setRating(4);
//			}
//			if (rating == "255") {
//				n.setRating(5);
//			}
			
			
		} catch (CannotReadException | IOException | TagException
				| ReadOnlyFileException | InvalidAudioFrameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();} catch (CannotWriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

	@Override
	public void loadAlbumNummers(Album a) {
		// TODO Auto-generated method stub
		
	}
}
